/*
  NewPromise板块
 */
class NewP {
  static PENDING = 'pending'
  static FULFILLED = 'fulfilled'
  static REJECT = 'reject'
  constructor(exector) {
    this.status = NewP.PENDING
    this.callbacks = []
    this.value = null
    try {
      exector(this.resolve.bind(this), this.reject.bind(this))
    } catch (error) {
      this.reject(error)
    }
  }

  resolve(value) {
    if (this.status === NewP.PENDING) {
      this.status = NewP.FULFILLED
      this.value = value
      setTimeout(() => {
        this.callbacks.map(callback => {
          callback.onfulfilled(this.value)
        })
      })
    }
  }
  reject(reason) {
    if (this.status === NewP.PENDING) {
      this.status = NewP.REJECT
      this.value = reason
      setTimeout(() => {
        this.callbacks.map(callback => {
          callback.onrejected(this.value)
        })
      });
    }
  }

  then(onfulfilled, onrejected) {
    if (typeof onfulfilled !== 'function') {
      // 如果不是一个函数, 就不用处理
      onfulfilled = () => { }
    }

    if (typeof onrejected !== 'function') {
      // 如果reject不是一个函数, 不用处理
      onrejected = () => { }
    }

    return new NewP((resolve, reject) => {
      if (this.status === NewP.FULFILLED) {
        setTimeout(() => {
          try {
            resolve(this.value)
          } catch (error) {
            reject(error)
          }
        })
      }

      if (this.status === NewP.PENDING) {
        this.callbacks.push({
          onfulfilled: value => {
            try {
              onfulfilled(value)
            } catch (error) {
              onrejected(error)
            }
          },
          onrejected: reason => {
            try {
              onrejected(reason)
            } catch (error) {
              onrejected(error)
            }
          }
        })
      }

      if (this.status === NewP.REJECT) {
        setTimeout(() => {
          try {
            resolve(this.value)
          } catch (error) {
            reject(error)
          }
        })
      }
    })
  }
}
/*
           FULFILLED(.then() 方法)
PENDING =>
           REJECTED(.catch() 方法)

 */

console.log(new Promise((resolve, reject) => { }));
console.log(new Promise((resolve, reject) => { resolve('hahah') }));
console.log(
  new Promise((resolve, reject) =>
  { reject('wowowow') }).catch(err => {
    console.log(err);
  })
)
